package hibernate;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import controller.Index;
import pojo.Products;
import pojo.User;
import pojo.Wishlist;
import dao.WishListDAO;

@Repository("WishListDAO")
public class HibernateWishListDAO implements WishListDAO {
	private SessionFactory sessionFactory;
	private static final Logger logger = Logger.getLogger(HibernateWishListDAO.class);
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	
	
	@Transactional
	public List<Wishlist> getWishlListByUser(User user) {
		Query query = sessionFactory.getCurrentSession().createQuery("from Wishlist w where w.user.memberid= " + user.getMemberid());
		return query.list();
	}
	
	@Transactional
	public boolean addWishlist(Wishlist wishlist) {
		Session session = sessionFactory.getCurrentSession();
        try
        {
            session.save(wishlist);
            logger.info("save wishlist to database completed");
            return true;
        }
        catch(HibernateException e)
        {
            System.err.print(e);
            logger.error("Error, this is it :",e);
        }
        return false;
	}


	@Transactional
	public boolean removeWishListByProductid(String productid) {
		Session session = sessionFactory.getCurrentSession();
		String hql = "delete from Wishlist w where w.products.productid = " +productid;
		try
        {
			Query query = session.createQuery(hql);
			query.executeUpdate();
			logger.info("Delete wishlist from database completed");
			return true;
        } catch(HibernateException e)
        {
        	logger.error("Delete wishlist from database got Error, this is it :",e);
            System.err.print(e); 
        }
		return false;
	}

}
